import { defineStore } from 'pinia'
import { Profile } from "@/types/user";
import request from "@/utils/request";
import { ApiRes } from "@/types/data";
import { saveProfile, getProfile, removeProfile } from '@/utils/storage'

export default defineStore('user', {
  state: () => {
    return {
      // profile: {} as Profile
      profile: getProfile()
    }
  },
  getters: {
    // 判断是否登录
    isLogin(): boolean {
      return this.profile.token ? true : false
    }
  },
  actions: {
    async login (account: string, password: string) {
      const res = await request.post<ApiRes<Profile>>('/login', {
        account,
        password
      })

      this.profile = res.data.result

      // 存储到本地
      saveProfile(res.data.result)
    },
    // 退出
    logout() {
      // 删除本地个人信息
      removeProfile()
      // 清空用户仓库中的profile
      this.profile = {}
    }
  }
  
})